/*
 * @Description:
 * @Author: 仲灏<izhaong 164165005@qq.com>
 * @Date: 2020-12-09 14:01:45
 * @LastEditors: 仲灏<izhaong 164165005@qq.com>
 * @LastEditTime: 2020-12-18 10:34:54
 */
var express = require("express");
var router = express.Router();
const axios = require("axios");
const shell = require("shelljs");

/* GET home page. */
router.post("/handle-srs", async function (req, res, next) {
  const { token } = req.headers;
  const { projectId = "0", handle = "create", cameraId = 1 } = req.body;
  const containerID = "e5e1135e7cf6";

  const hasAuth = await checkAuth(projectId, token);
  if (hasAuth) {
    console.log("start--------");
    // -crf 200
    let exec;
    if (handle === "create") {
      exec = `docker exec ${containerID} /bin/bash -c 'ffmpeg -rtsp_transport tcp -i rtsp://admin:hk888888@ztzyjc.3322.org:9002/Streaming/channels/${cameraId}01  -c:v libx264  -acodec aac -f flv rtmp://127.0.0.1:1935/live/mystream${cameraId}'`;

      shell.exec(exec, { silent: true }, function (error, stdout, stderr) {
        console.log(`callback--------------${error, stderr}`);
      });
    }
    if (handle === "playback") {
      const datetime = JSON.parse(
        req.body.datetime || ["20201214t000000z", "20210113t000000z"]
      );
      
      exec = `docker exec ${containerID} /bin/bash -c 'ffmpeg -rtsp_transport tcp -i "rtsp://admin:hk888888@ztzyjc.3322.org:9002/Streaming/tracks/${cameraId}01?starttime=${datetime[0]}&endtime=${datetime[1]}" -c copy -f flv rtmp://127.0.0.1:1935/live/mytrack${datetime[0]}'`;

      shell.exec(exec, { silent: true }, function (error, stdout, stderr) {
        console.log(`callback--------------${error, stderr}`);
      });
    }
    console.log(exec)
    console.log("over--------");

    res.send({
      code: 200,
      message: "已向转流服务器发送执行命令, 请稍后~",
    });
  } else {
    res.send({
      code: 401,
      message: "警告~,你并无权限执行此操作",
    });
  }
});

const checkAuth = (projectId, token) => {
  return axios({
    url: `http://10.2*.**.**:8333/wxwl-construction/aisite/fvs/device/page?page=1&limit=1&projectId=${projectId}`,
    timeout: 10000,
    headers: {
      token,
    },
  }).then(({ data }) => {
    return data && data.code == 0;
  });
};

module.exports = router;
